package com.ml.doctor.view;

import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ml.doctor.R;
import com.ml.doctor.utils.DisplayUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO:功能说明
 *
 * @author: kun
 * @date: 2015-12-10 21:28
 */
public class FlowLayout extends LinearLayout implements View.OnClickListener {

    private int width;
    private List<ItemData> itemDataList = new ArrayList<>();
    private ServiceItemClickListener listener;
    private int textViewID = R.layout.txt_tag;
    private int horizontal = 8;
    private int vertical = 6;

    public FlowLayout(Context context) {
        this(context, null);
    }

    public FlowLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOrientation(VERTICAL);
        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                width = getWidth();
                if (width > 0) {
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                        getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    } else {
                        getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                    setContent();
                }
            }
        });
    }

    protected Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what != 1)
                return;
            setContent();
        }
    };


    public void setContent(List<String> contents) {
        itemDataList.clear();
        this.removeAllViews();
        for (String content : contents) {
            itemDataList.add(new ItemData(content, "", ""));
        }
        handler.sendEmptyMessage(1);
    }

    public void setItemData(List<ItemData> itemDatas) {
        itemDataList.clear();
        this.removeAllViews();
        if (itemDatas != null) {
            itemDataList.addAll(itemDatas);
        }
        handler.sendEmptyMessage(1);
    }

    public void setTextViewID(int id) {
        this.textViewID = id;
    }

    public void setOnServiceItemClickListener(ServiceItemClickListener listener) {
        this.listener = listener;
    }

    public void setHorizontalSpace(int horizontalSpace) {
        horizontal = horizontalSpace;
    }

    public void setVerticalSpace(int verticalSpace) {
        vertical = verticalSpace;
    }


    private void setContent() {
        if (width <= 0) {
            return;
        }
        removeAllViews();
        int horizontalSpace = DisplayUtils.dip2px(getContext(), horizontal);
        int verticalSpace = DisplayUtils.dip2px(getContext(), vertical);
        float lineWidth = 0;
        int lineCount = 0;
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        LinearLayout mLinearLayout = new LinearLayout(getContext());
        mLinearLayout.setOrientation(HORIZONTAL);
        addView(mLinearLayout, layoutParams);

        LayoutParams textLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        textLayoutParams.setMargins(0, 0, horizontalSpace, 0);

        for (int i = 0; i < itemDataList.size(); i++) {
            TextView textView = (TextView) LayoutInflater.from(getContext()).inflate(textViewID, null);
            if (itemDataList.get(i).content == null) {
                itemDataList.get(i).content = "";
            }
            textView.setText(itemDataList.get(i).content);
            textView.setOnClickListener(this);
            textView.setTag(i);
            if (!TextUtils.isEmpty(itemDataList.get(i).backgroundColor)) {
//                GradientDrawable myGrad = (GradientDrawable) textView.getBackground();
//                myGrad.setColor(Color.parseColor(itemDataList.get(i).backgroundColor));
                textView.setBackgroundColor(Color.parseColor(itemDataList.get(i).backgroundColor));
            }
            if (!TextUtils.isEmpty(itemDataList.get(i).textColor)) {
                textView.setTextColor(Color.parseColor(itemDataList.get(i).textColor));
            }
            float textLength = measureText(textView, itemDataList.get(i).content) + textView.getPaddingLeft() + textView.getPaddingRight();
            if (textLength > width) {
                textLength = width - horizontalSpace * 2;
            }
            lineCount++;
            lineWidth += textLength + lineCount * horizontalSpace;

            if (lineWidth > width) {
                mLinearLayout = new LinearLayout(getContext());
                mLinearLayout.setOrientation(HORIZONTAL);
                layoutParams.setMargins(0, verticalSpace, 0, 0);
                addView(mLinearLayout, layoutParams);

                lineCount = 1;
                lineWidth = measureText(textView, itemDataList.get(i).content);
            }
            mLinearLayout.addView(textView, textLayoutParams);
        }

    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onClick(View v) {
        if (listener != null) {
            listener.onServiceItemClick((Integer) v.getTag(), (TextView) v);
        }
    }

    public float measureText(TextView textView, String text) {
        return textView.getPaint().measureText(text);
    }

    public interface ServiceItemClickListener {
        void onServiceItemClick(int position, TextView v);
    }

    public class ItemData {
        public String content;
        public String backgroundColor;
        public String textColor;

        public ItemData(String content, String backgroundColor, String textColor) {
            this.content = content;
            this.backgroundColor = backgroundColor;
            this.textColor = textColor;
        }
    }
}
